package cn.com.agree.order.controller;

import cn.com.agree.order.client.ProductClient;
import cn.com.agree.order.dto.CartDTO;
import cn.com.agree.order.entity.ProductInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

/**
 * Descriptions...
 *
 * @author sun.ys
 * @date 2020/8/26.
 */
@RestController
@Slf4j
public class ClientController {
    
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    
    @Autowired
    private RestTemplate restTemplate3;
    
    
    @Autowired
    private ProductClient productClient;
    
    @GetMapping("/getProductMsg")
    public String getProductMsg() {
        
        
        //1.第一种方式(直接使用restTemplate，url写死)
   /* RestTemplate  restTemplate = new RestTemplate();
    String  response =  restTemplate.getForObject("http://127.0.0.1:8080/msg",String.class);
    log.info("response={}",response);*/
        
        
        //2.第二种方式（利用loadBalancerClient通过应用名获取url，然后使用restTemplate2）
        RestTemplate restTemplate2 = new RestTemplate();
        
        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
        String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort() + "/msg");
        String response2 = restTemplate2.getForObject(url, String.class);
        log.info("response2={}", response2);
        
        
        //3.第三种方式
        
        String response3 = restTemplate3.getForObject("http://PRODUCT/msg", String.class);
        
        log.info("response3 ={}", response3);
        
        return response3;
    }
    
    @GetMapping("/getdemo")
    public String getProductMsgs() {
        
        String response = productClient.productMsg();
        log.info("response ={}", response);
        return response;
    }
    
    
    @GetMapping("/getProductList")
    
    public   String  getProductList(){
        List<ProductInfo> productInfoList = productClient.listForOrder(Arrays.asList("164103465734242707"));
        log.info("response ={}", productInfoList);
        return  "ok";
    }
    
    @GetMapping("/productDecreaseStock")
    public  String productDecreaseStock(){
    
        productClient.decreaseStock(Arrays.asList(new CartDTO("164103465734242707",3)));
        
        return  "ok";
    }
    
    
}
